<!--
 * @Author: guo-chengjiang 1029833238@qq.com
 * @Date: 2025-03-22 14:56:14
 * @LastEditors: guo-chengjiang 1029833238@qq.com
 * @LastEditTime: 2025-03-23 14:30:33
 * @FilePath: \vue_demo\src\views\Login.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!-- Login.vue -->
<template>
  <div class="login-container">
    <el-form label-position="top" class="login-form">
      <el-form-item label="用户名">
        <el-input v-model="form.username" placeholder="请输入注册时的用户名"></el-input>
      </el-form-item>
      <el-form-item label="年龄">
        <el-input 
          v-model.number="form.age" 
          type="number"
          placeholder="请输入注册时的年龄"
        ></el-input>
      </el-form-item>
      <el-button 
        type="primary" 
        @click="handleLogin"
        :loading="loading"
      >登录</el-button>
    </el-form>
  </div>
</template>
  
<script>
export default {
  data() {
    return {
      loading: false,
      form: {
        username: '',
        age: null
      }
    }
  },
  methods: {
    async handleLogin() {
      // 前端基础验证
      if (!this.form.username || !this.form.age) {
        this.$message.error('用户名和年龄不能为空')
        return
      }

      this.loading = true
      try {
        // 调用验证接口
        const response = await this.$axios.get('/user/page', {
          params: {
            pageNumber: 1,
            pageSize: 10,
            userName: this.form.username,
            age: this.form.age
          },
          headers: {
            Authorization: 'Bearer ' + localStorage.getItem('token')
          }
        })

        // 处理验证结果
        if (response.data.code === 0) {
          const validUsers = response.data.data.records.filter(user => 
            user.name === this.form.username && 
            user.age === this.form.age
          )

          if (validUsers.length > 0) {
            localStorage.setItem('currentUser', JSON.stringify(validUsers[0]))
            this.$router.push('/wechat')
          } else {
            this.$message.error('用户不存在或信息不匹配')
          }
        } else {
          this.$message.error(response.data.msg || '验证失败')
        }
      } catch (error) {
        console.error('登录错误:', error)
        this.$message.error('登录失败，请检查网络连接')
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 100px auto;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.el-button {
  width: 100%;
  margin-top: 20px;
}
</style>